<template>
    <div class="permission">
        <n-form :model="model">
            <n-form-item label="名称">
                <n-input v-model:value="model.name" @keydown.enter.prevent />
            </n-form-item>
            <n-form-item label="描述">
                <n-input v-model:value="model.description" @keydown.enter.prevent />
            </n-form-item>
            <n-form-item label="权限">
                <n-tree-select multiple cascade checkable check-strategy="all" :options="options" :value="model.permissions" @update:value="onUpdateValue" />
            </n-form-item>

            <n-space>
                <n-button @click="onAdd">新增</n-button>
                <n-button type="tertiary" @click="onEdit">修改</n-button>
            </n-space>
        </n-form>

        <h4 @click="onLoad">全部</h4>
        <n-space>
            <n-tag closable @close="onDel(i)" v-for="i in list" :key="i._id" @click="onShow(i)">{{ i.name }}</n-tag>
        </n-space>
    </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import { NForm, NInput, NButton, NFormItem, NSpace, NTag, NTreeSelect } from "naive-ui";
import { useRoleStore } from "@/stores/role";
import { usePermissionStore } from "@/stores/permission";
import { listToTree } from "@/comm/tree";
const roleStore = useRoleStore();
const permissionStore = usePermissionStore();

onMounted(() => {
    roleStore.load();
});

const onAdd = async () => {
    let param = {
        ...model.value
    };
    let res = await roleStore.add(param);
    console.log(res);
    roleStore.load();
};

const onEdit = async () => {
    let param = {
        ...model.value
    };
    let res = await roleStore.update(param);
    console.log(res);
    roleStore.load();
};

interface ModelType {
    name: string;
    description: string;
    permissions: string[];
    _id: string;
}

const model = ref<ModelType>({
    name: "",
    description: "",
    permissions: [],
    _id: ""
});
const list = computed(() => roleStore.list);

// const value = ref<string[]>([]);
const options = computed(() => {
    // return permissionStore.list.map(i => {
    //     return { key: i._id, label: i.name };
    // })
    return listToTree(permissionStore.list);
});
const onUpdateValue = (val: any) => {
    model.value.permissions = val;
};

const onDel = async (item: any) => {
    console.log(item);
    let res = await roleStore.remove(item._id);
    console.log(res);
    roleStore.load();
};

const onShow = (item: any) => {
    model.value.name = item.name;
    model.value.description = item.description;
    model.value._id = item._id;
    model.value.permissions = item.permissions || [];
};

const onLoad = () => {
    roleStore.load();
};
</script>
